package com.hmall.utils;

import cn.hutool.core.lang.UUID;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyuncs.exceptions.ClientException;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
@Slf4j
public class AliOssUtil {




    private final static String bucketName = "managent"; //桶名称
    private final static String endpoint = "oss-cn-beijing.aliyuncs.com"; //桶节点域名
    private final static String accessKeyId = "LTAI5tLwKqzTx1sgzWwX2piu"; //密钥
    private final static String accessKeySecret = "biIVuWRSiGYkzeEsvEbZGSi2wEQBm9"; //密钥


    /**
     * 上传文件
     *
     * @param inputStream 文件流对象
     * @return
     */
    @SneakyThrows
    public static String upload(InputStream inputStream) {

        String objectName = UUID.fastUUID().toString(true);

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        //判断容器是否存在,不存在就创建
        if (!ossClient.doesBucketExist(bucketName)) {
            ossClient.createBucket(bucketName);
            CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
            //设置问公共可读
            createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
            ossClient.createBucket(createBucketRequest);
        }


        // 上传文件
        PutObjectRequest request = new PutObjectRequest(bucketName, objectName, inputStream);
        PutObjectResult result = ossClient.putObject(request);

        if (result != null) {
            log.info("OSS文件上传成功：{}", objectName);
        }

        //文件访问路径规则 https://BucketName.Endpoint/ObjectName
        return "https://" + bucketName + "." + endpoint + "/" + objectName;
    }
 }

